package net.qhzw.geologr5.gis.service.system.component;


import lombok.extern.slf4j.Slf4j;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/***
 * 文件模板
 */

@Component
@Slf4j
public class FileTemplate {


    @Value("${fileServer.url}")
    private String fileUrl;

    private final String configFile = new ClassPathResource("tracker.conf").getPath();

    /***
     * 文件上传服务器
     * @param file
     * @return 上传后文件路径
     * @throws IOException
     * @throws MyException
     */
    public String fileUpload(MultipartFile file) throws IOException, MyException {
        String imgUrl = fileUrl;
        if (file != null) {
            log.info("multipartFile: {}, file.size: {}", file.getName(), file.getSize());
            //String configFile = new ClassPathResource("tracker.conf").getPath();
            ClientGlobal.init(configFile);
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageClient storageClient = new StorageClient(trackerServer, null);
            String filename = file.getOriginalFilename();
            String extName = StringUtils.substringAfterLast(filename, ".");
            String[] upload_file = storageClient.upload_file(file.getBytes(), extName, null);
            imgUrl = fileUrl;
            for (int i = 0; i < upload_file.length; i++) {
                String path = upload_file[i];
                imgUrl += "/" + path;
            }
        }
        log.info("fileUrl: {}", imgUrl);
        return imgUrl;
    }


    /***
     * 上传文件不带 ip 端口
     * @param file
     * @return
     * @throws IOException
     * @throws MyException
     */
    public String uploadFile(MultipartFile file) throws IOException, MyException {
        String filePath = "";
        if (file != null) {
            log.info("multipartFile: {}, file.size: {}", file.getName(), file.getSize());
            ClientGlobal.init(configFile);
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageClient storageClient = new StorageClient(trackerServer, null);
            String filename = file.getOriginalFilename();
            String extName = StringUtils.substringAfterLast(filename, ".");
            String[] upload_file = storageClient.upload_file(file.getBytes(), extName, null);
            for (int i = 0; i < upload_file.length; i++) {
                String path = upload_file[i];
                filePath += "/" + path;
            }
        }
        log.info("filePath: {}", filePath);
        return filePath;
    }





    /***
     * 文件上传
     * @param file
     * @return
     */
    public String uploadLocal(MultipartFile file) throws IOException {
        log.info("文件上传", file.getOriginalFilename());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(new Date());
        //上传文件
        String filename = file.getOriginalFilename(); //获取文件名，带后缀
        String fileType = filename.substring(filename.lastIndexOf("."));
        String path = "D://tem//" + fileType + "//" + date + "//";
        File folderPath = new File(path);
        //查询文件夹是否存在
        if (!folderPath.exists() && !folderPath.isDirectory()) {
            folderPath.mkdirs();
            log.info("目录不存在，创建新文件夹");
        }
        File filePath = new File(path + filename);
        log.info("上传url:{}", filePath);
        //将上传的文件写到服务器上指定的文件路径
        file.transferTo(filePath);
        return filePath.getPath();
    }


    /***
     * 文件下载
     */
    public JsonResult download(String fileId, HttpServletResponse response) {
        InputStream input = null;
        OutputStream output = null;
        try {
            String subFileUrl = subFileUrl(fileId);
            //初始化fastdfs客户端配置文件
            ClientGlobal.init(configFile);
            //获取trackerServer
            TrackerClient tracker = new TrackerClient();// 创建tracker客户端对象
            TrackerServer trackerServer = tracker.getConnection();//获得tracker连接对象
            //获取storageClient（通过trackerServer 和 storageServer：null）
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);//通过tracker服务器返回storage服务器对象（客户端）
            byte[] bytes = client.download_file1(subFileUrl);//记得要传文件id返回字节流
            input = new ByteArrayInputStream(bytes);
            output = response.getOutputStream();
            IOUtils.copy(input, output);
            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }





    /*public JsonResult download(HttpServletResponse response, String source) throws IOException {
        byte[] buffer = new byte[1024 * 10];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            File tempFile = new File(source.trim());
            //获取文件名
            String fileName = tempFile.getName();
            // 如果文件名不为空，则进行下载
            if (!StringUtils.isEmpty(fileName)) {
                //设置文件路径
                File file = new File(source);
                // 如果文件名存在，则进行下载
                if (file.exists()) {
                    // 配置文件下载
                    response.setHeader("content-type", "application/octet-stream");
                    response.setContentType("application/octet-stream");
                    // 下载文件能正常显示中文
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                    // 实现文件下载
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return JsonResult.success("Download the successfully!");
                }
            }
            return JsonResult.error("文件不存在");
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }*/


    /****
     * 截取字符串
     * @param fileUrl
     * @return
     */
    private String subFileUrl(String fileUrl) {
        String[] split = fileUrl.split("/");
        StringBuffer sb = new StringBuffer();
        for (int i = 3; i < split.length; i++) {
            String s = split[i];
            System.out.println(s);
            if (split.length - 1 == i) {
                sb.append(s);
            } else {
                sb.append(s).append("/");
            }
        }
        return sb.toString();
    }

    /****
     * 截取文件路径
     * @param source
     * @return
     */
    private Map<String, String> subFilePath(String source) {
        Map<String, String> result = new HashMap<>();
        String[] split = source.split("/");
        StringBuffer sb = new StringBuffer();
        for (int i = 3; i < split.length; i++) {
            String s = split[i];
            if (i <= split.length - 2) {
                sb.append(s).append("/");
            }
            if (i == split.length - 1) {
                log.info("fileName: {}", split[i]);
                result.put("fileName", split[i]);
            }
        }
        result.put("path", sb.toString());
        return result;
    }

}
